package com.sprite.email.controller;

import com.sprite.email.entity.Mail;
import com.sprite.email.factory.MailStrategyFactory;
import com.sprite.email.vo.Email;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@RestController @RequestMapping("mail") public class MailController {

    private Logger logger = LoggerFactory.getLogger(MailController.class);

    @Autowired private MailStrategyFactory mailStrategyFactory;

    @Value("${spring.mail.username}") private String from;

    @RequestMapping(value = "send", method = RequestMethod.POST)
    @ResponseBody public String send(
            @RequestBody Email email, HttpServletResponse response) {
        try {

            Mail mail = new Mail.Builder()
                    .title(email.getTitle())
                    .to(email.getTo())
                    .content(email.getContent())
                    .templateName(email.getTemplateName())
                    .maps(email.getMaps())
                    .build();

            mailStrategyFactory
                    .getStrategy(email.getContentType())
                        .sendMail(from, mail);

            return "success";
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.setStatus(500);
            return "fail";
        }
    }
}
